-- UINationSelect
-- Created by chengb Jul/31/2015
-- 国籍选择界面

UINationSelect = class("UINationSelect", function()
    return cc.Layer:create();
end);

function UINationSelect.create(dungeonId)
    return UINationSelect.new(dungeonId);
end

-- 每行最多可显示的国籍个数
local MAX_COLUMN_NUM = 5;

-- 每页的行数
local PAGE_ROW       = 5;

-- 构造函数
function UINationSelect:ctor(dungeonId)
    -- 初始化
    self:setName("UINationSelect");
    local node = cc.CSLoader:createNode("layout/ranklist/NationSelect.csb");
    self:addChild(node);
    self.node = node;
    self.dungeonId = dungeonId;

    -- 获取可选择的国籍列表
    self.nationList = TopM.getNationIndexList();

    -- 当前选择的国籍图标
    self.selectedItem = nil;

    local uiComment = UIMgr.getCurrentScene():getFormByName("UIComment");
    if uiComment then
        -- 评论界面打开的
        self:setLocalZOrder(UIMgr.BONUS_NOTIFY_ZORDER + 1);
    else
        -- 设置层级
        self:setLocalZOrder(UIMgr.TOP_MENU_ZORDER + 1);
    end

    -- 注册点击事件
    self:registerTouchEvent();

    -- 初始化
    self:init();

    -- 重绘
    self:redraw();

    -- 适配
    self:resize();
end

-- 适配
function UINationSelect:resize()
    local node = self.node;

    -- bg居中显示并充满整个屏幕
    AlignM.fitToScreen(node, "bg");

    -- CT居中并缩放至合适大小
    AlignM.alignToCenter(node, "CT");

    -- BT置于底部并缩放至合适大小
    AlignM.alignToBottomCenter(node, "BT");
end

-- 注册点击事件
function UINationSelect:registerTouchEvent()
    -- 注册确定按钮点击事件
    local btnOk = findChildByName(self.node, "BT/btn_ok");
    local function onOkClick(sender, eventType)
        if eventType == ccui.TouchEventType.ended then
            AudioM.playFx("button_click");
            if self.selectedItem == nil then
                -- 未选择，直接关闭界面
                closeFormByName("UINationSelect");
                return;
            end

            -- 判断下是否超过了冷却时间
            local lastChangeTime = ME.user.dbase:query("nation_change_time") or 0;
            local coolTime = lastChangeTime + 86400 - TimeM.getServerTime();
            if coolTime > 0 then
                alert(string.format(getLocStr("change_nation_cool_time"), remainingTimeDesc(coolTime)));
            else
                -- 抛出选择国籍的事件
                local id = self.selectedItem:getTag();
                EventMgr.fire(event.SELECT_NATION, { ["id"] = id, ["dungeon_id"] = self.dungeonId, });
            end

            -- 关闭界面
            closeFormByName("UINationSelect");
        end
    end
    btnOk:addTouchEventListener(onOkClick);
    TextStyleM.setTextStyle(btnOk, TextStyleM.TEXT_SIZE_MIDDLE, TextStyleM.TEXT_COLOR_BROWN_YELLOW, true);
    btnOk:setTitleText(getLocStr("btn_text_ok"));

    -- 注册返回按钮点击事件
    local btnBack = findChildByName(self.node, "BT/btn_back");
    local function onBackClick(sender, eventType)
        if eventType == ccui.TouchEventType.ended then
            -- 关闭当前界面
            AudioM.playFx("button_return");
            closeFormByName("UINationSelect");
        end
    end
    AddBackEventHandler(self, btnBack, onBackClick);
    TextStyleM.setTextStyle(btnBack, TextStyleM.TEXT_SIZE_MIDDLE, TextStyleM.TEXT_COLOR_BROWN_YELLOW, true);
    btnBack:setTitleText(getLocStr("btn_text_back"));
end

-- 初始化
function UINationSelect:init()
    local scrollview = findChildByName(self.node, "CT/scrollview");
    scrollview:removeAllChildren();

    local itemNode = cc.CSLoader:createNode("layout/ranklist/NationItem.csb");
    local widget = replaceNodeWithWidget(itemNode);

    -- 图标间距
    local hGap = 15;
    local wGap = 15;

    -- 图标宽度
    local iconWidth  = 65;
    local iconHeight = 90;
    local itemNum = #self.nationList;

    local totalHeight = (math.ceil(itemNum/MAX_COLUMN_NUM))*(iconHeight + hGap);
    local areaWidth = scrollview:getContentSize().width;

    wGap = (areaWidth - iconWidth*MAX_COLUMN_NUM)/(MAX_COLUMN_NUM + 1);

    -- 设置滚动容器内部滚动区域的大小
    scrollview:setInnerContainerSize(cc.size(scrollview:getInnerContainerSize().width, totalHeight));

    for i, index in pairs(self.nationList) do
        local child = widget:clone();
        local x = (((i - 1) % MAX_COLUMN_NUM))*(iconWidth + wGap) + iconWidth/2 + wGap;
        local y = totalHeight - math.floor((i - 1)/MAX_COLUMN_NUM)*(iconHeight) - (iconHeight/2);
        child:setPositionX(x);
        child:setPositionY(y);

        local id = TopM.getNationIdByIndex(index);

        -- 初始化道具
        child:setTag(id);

        -- 选中光效
        local lightImg = findChildByName(child, "light");
        lightImg:setVisible(false);
        child.lightImg = lightImg;

        -- 国家图标
        local iconImg = findChildByName(child, "icon");
        local icon = TopM.queryNationality(id, "icon");
        iconImg:loadTexture(getNationalityIconPath(icon));
        child.iconImg = iconImg;
        child.initIconScale = iconImg:getScale();

        -- 国家名称
        local nameLabel = findChildByName(child, "name");
        local name = TopM.queryNationality(id, "name");
        TextStyleM.setTextStyle(nameLabel, TextStyleM.TEXT_SIZE_TINY, TextStyleM.TEXT_COLOR_WHITE, true, -2);
        nameLabel:setString(name);

        -- 注册图标点击事件
        local panel = findChildByName(child, "panel");
        local function onClick(sender, eventType)
            if eventType == ccui.TouchEventType.ended then
                AudioM.playFx("button_click");
                -- 重新绘制选中效果
                if self.selectedItem then
                    self.selectedItem.lightImg:setVisible(false);
                    self.selectedItem.iconImg:setScale(child.initIconScale);
                end

                -- 显示光效，图标略微缩小
                child.lightImg:setVisible(true);
                child.iconImg:setScale(0.95*child.initIconScale);
                self.selectedItem = child;
            end
        end
        panel:addTouchEventListener(onClick);

        scrollview:addChild(child);

        -- 每行显示一个分隔线
        if i % MAX_COLUMN_NUM == 1 then
            local lineImg = ccui.ImageView:create("images/ui/symbol/line_white.png");
            local posX = areaWidth/2;
            local posY = (child:getPositionY() - iconHeight/2) + 2;
            lineImg:setPosition(posX, posY);
            scrollview:addChild(lineImg);
        end
    end

    -- 默认滑到最顶端
    scrollToTop(scrollview);
end

-- 重绘
function UINationSelect:redraw()
    -- 获得当前用户的nationId如果
    local nationId = ME.user.dbase:query("nation_id");

    local scrollview = findChildByName(self.node, "CT/scrollview");
    if nationId ~= nil then
        local child = scrollview:getChildByTag(nationId);

        if child == nil then
            -- 出现了没有找到的情况，是海外列表中才有的地区导致的
            -- 正常情况不会出现，这里容错，统一处理成默认值
            child = scrollview:getChildByTag(0);
        end

        -- 重新绘制选中效果
        if self.selectedItem then
            self.selectedItem.lightImg:setVisible(false);
            self.selectedItem.iconImg:setScale(child.initIconScale);
        end

        -- 显示光效，图标略微缩小
        child.lightImg:setVisible(true);
        child.iconImg:setScale(0.95*child.initIconScale);
        self.selectedItem = child;

        -- 显示当前信息的国家名称
        local name = TopM.queryNationality(nationId, "name");

        local nationLabel = findChildByName(self.node, "CT/nation_name_label");
        TextStyleM.setTextStyle(nationLabel, TextStyleM.TEXT_SIZE_MIDDLE, TextStyleM.TEXT_COLOR_WHITE, true, -2);
        nationLabel:setString(string.format(getLocStr("nation_name"), name));
        nationLabel:setVisible(true);

        -- 滑动到合适的位置
        self:scrollTo(nationId);
    end
end

-- 移动中心
function UINationSelect:scrollTo(nationId)
    local scrollview = findChildByName(self.node, "CT/scrollview");

    local percent = 0;
    if nationId >  MAX_COLUMN_NUM*PAGE_ROW then
        percent = nationId * 100 / (MAX_COLUMN_NUM*PAGE_ROW);
    end

    -- scrollview:jumpToPercentVertical(150);
    scrollview:scrollToPercentVertical(percent, 0.1, true);
end





